package idv.arthur.work;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;

public class QuerySquad extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	
    public QuerySquad() {
        super();
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	doPost(request,response);
    }

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		Widgets wid = new Widgets();
		request.setCharacterEncoding( wid.UIcodeSet );
		response.setContentType("application/json");
		response.setCharacterEncoding( wid.UIcodeSet );		
		
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		String errPars = "}";
		
		String fromCall = request.getParameter("fc");		//供Servlet識別從那個UI來呼叫
		
		String strSQL = "SELECT COUNT(*) FROM squad WHERE bssid=? AND subsysid=?";

		final String bssId = request.getParameter("bssId");
		String subSysId = request.getParameter("subSysId");
		
		int arrayCount = 3;
		
		if ( "mappingEnvSquad".equalsIgnoreCase(fromCall) ) {
			arrayCount = 4;
		}
		
		ResultTableSet resultTableSet = new ResultTableSet();
		ArrayList<InfoStruc> infoStrucs = new ArrayList<InfoStruc>();
		
		String sord = request.getParameter("sord");
		String sidx =  request.getParameter("sidx");
		
		int total_pages = 1;
		int count = 0; 
		int page = 1;
		int limit = 10;
		if ("".equalsIgnoreCase(sidx)|| sidx==null|| "my_checkbox".equalsIgnoreCase(sidx)) {
			sidx = "squadname";
		} 
		if ("".equalsIgnoreCase(sord)|| sord==null) {
			sord = "ASC";
		} else {
			page = Integer.parseInt(request.getParameter("page"));
			limit = Integer.parseInt(request.getParameter("rows"));
		}
		
		try {
			conn = wid.getConn(true);	
			ps = conn.prepareStatement(strSQL);
			ps.setString(1, bssId);
			ps.setString(2, subSysId);
			rs = ps.executeQuery();
			rs.next();
			count  = rs.getInt(1);
			
			if ( count  != 0 ) {
				
				if (limit  < count) {
					total_pages = (count / limit)+1;	
				}
				
				if ( conn.getMetaData().getDatabaseProductName().contains( "MySQL" ) ) {
					if ( "mappingEnvSquad".equalsIgnoreCase(fromCall) ) {
						strSQL = "SELECT mpsquadenv.squadid as 'j',squad.subsysid,squad.squadid,squad.squadname,squad.squadpath FROM squad LEFT JOIN mpsquadenv ON squad.bssid = mpsquadenv.bssid AND squad.subsysid = mpsquadenv.subsysid AND squad.squadid = mpsquadenv.squadid AND mpsquadenv.envid=? WHERE squad.bssid = ? AND squad.subsysid = ? ORDER BY "+sidx+" "+sord+" LIMIT "+(limit*page-limit)+","+ limit;
						ps = conn.prepareStatement(strSQL);
						ps.setString(1, request.getParameter("envId"));
						ps.setString(2, bssId);
						ps.setString(3, subSysId);
					} else if ( "mappingSqGroupSquad".equalsIgnoreCase(fromCall) ) {
						strSQL = "SELECT t1.squadid,t2.squadname FROM mpsquadgroupsquads t1, squad t2 WHERE t1.bssid=t2.bssid AND t1.subsysid=t2.subsysid AND t1.squadid=t2.squadid AND t1.bssid=? AND t1.subsysid=? AND t1.sqgruseqid=?";
						ps = conn.prepareStatement(strSQL);
						ps.setString(1, bssId);
						ps.setString(2, subSysId);
						ps.setString(3, request.getParameter("sqGroupId"));
					} else if ( "mappingSquadHost".equalsIgnoreCase(fromCall) ) {
						strSQL = "SELECT t1.squadid,t2.squadname FROM mpsquadenv t1, squad t2 WHERE t1.bssid=t2.bssid AND t1.subsysid=t2.subsysid AND t1.squadid=t2.squadid AND t1.bssid=? AND t1.subsysid=? AND t1.envid=?";
						ps = conn.prepareStatement(strSQL);
						ps.setString(1, bssId);
						ps.setString(2, subSysId);
						ps.setString(3, request.getParameter("envId"));
					} else {
						strSQL = "SELECT t1.squadid, t1.squadname, t1.squadpath,t2.bssid,t2.bssname,t3.subsysid,t3.subsysname FROM squad t1,bss t2,subsys t3 WHERE t1.bssid=? AND t1.subsysid=? AND t1.bssid=t2.bssid AND t1.subsysid=t3.subsysid ORDER BY "+sidx+" "+sord+" LIMIT "+(limit*page-limit)+","+ limit;
						ps = conn.prepareStatement(strSQL);
						ps.setString(1, bssId);
						ps.setString(2, subSysId);
					}					
				} else if ( conn.getMetaData().getDatabaseProductName().contains( "Informix" ) ) {
					if ( "mappingEnvSquad".equalsIgnoreCase(fromCall) ) {	//維護環境下轄資源群組
						strSQL = "SELECT SKIP "+(limit*page-limit)+" FIRST "+ limit +" t2.squadid,t1.subsysid,t1.squadid,t1.squadname,t1.squadpath FROM squad t1, OUTER mpsquadenv t2 WHERE t1.bssid = t2.bssid AND t1.subsysid = t2.subsysid AND t1.bssid=? AND t1.subsysid=? AND t1.squadid = t2.squadid AND t2.envid=? ORDER BY "+sidx+" "+sord;;
					} else if ( "mappingSqGroupSquad".equalsIgnoreCase(fromCall) ) { 	//維護群組集合下轄群組
						strSQL = "SELECT SKIP "+(limit*page-limit)+" FIRST "+ limit +" t2.squadid,t1.subsysid,t1.squadid,t1.squadname FROM squad t1, OUTER mpsquadgroupsquads t2 WHERE (t1.bssid = t2.bssid AND t1.subsysid = t2.subsysid AND t1.bssid=? AND t1.subsysid=? AND t1.squadid=t2.squadid AND t2.sqgruseqid=?) ORDER BY "+sidx+" "+sord;
					} else if ( "mappingSquadHost".equalsIgnoreCase(fromCall) ) { 	//維護資源群組下轄主機
						strSQL = "SELECT t1.squadid,t2.squadname FROM mpsquadenv t1, squad t2 WHERE t1.bssid=t2.bssid AND t1.subsysid=t2.subsysid AND t1.squadid=t2.squadid AND t1.bssid=? AND t1.subsysid=? AND t1.envid=?";
					} else {	//維護資源群組
						strSQL = "SELECT SKIP "+(limit*page-limit)+" FIRST "+ limit +"  t1.squadid, t1.squadname, t1.squadpath,t2.bssid,t2.bssname,t3.subsysid,t3.subsysname FROM squad t1,bss t2,subsys t3 WHERE t1.bssid=? AND t1.subsysid=? AND t1.bssid=t2.bssid AND t1.subsysid=t3.subsysid ORDER BY "+sidx+" "+sord;
					}
					ps = conn.prepareStatement(strSQL);
					ps.setString(1, bssId);
					ps.setString(2, subSysId);
					if ( "mappingSqGroupSquad".equalsIgnoreCase(fromCall) ) {		//維護群組集合下轄群組
						ps.setString(3, request.getParameter("sqGroupId"));						
					} else if ( "mappingEnvSquad".equalsIgnoreCase(fromCall) || "mappingSquadHost".equalsIgnoreCase(fromCall) ) {	//維護環境下轄資源群組    維護資源群組下轄主機
						ps.setString(3, request.getParameter("envId") );						
					}
				}
				
				rs = ps.executeQuery();
				ArrayList<Rows> rows = new ArrayList<Rows>();
				
				while ( rs.next() ) {
					Rows row = new Rows();
					String[] cell = null;
					row.setId(rs.getString("squadid"));
					cell = new String[arrayCount];
					
					if ( "mappingEnvSquad".equalsIgnoreCase(fromCall)  || "mappingSqGroupSquad".equalsIgnoreCase(fromCall) ) {
						cell[0] = (rs.getString(1)==null?null:rs.getString("squadid"));
						cell[1] = rs.getString("squadid");
						cell[2] = wid.DB2UI( rs.getString("squadname"),conn.getMetaData().getDatabaseProductName() );
						if ( "mappingEnvSquad".equalsIgnoreCase(fromCall) ) {	//僅環境的畫面 需要看部署路徑
							cell[3] = rs.getString("squadpath");	
						}
					} else if ( "mappingSquadHost".equalsIgnoreCase(fromCall) ) {
						InfoStruc infoStruc = new InfoStruc();
						infoStruc.setId(rs.getString("squadid"));
						infoStruc.setName( wid.DB2UI( rs.getString("squadname"),conn.getMetaData().getDatabaseProductName() ) );
						infoStrucs.add(infoStruc);
					} else {
						cell[0] = rs.getString("squadid");
						cell[1] = wid.DB2UI( rs.getString("squadname"),conn.getMetaData().getDatabaseProductName() );
						cell[2] = rs.getString("squadpath");	
					}
					
					row.setCell(cell);
					rows.add(row);
				}
				resultTableSet.setRows(rows);
			} else {
				page =0;
				total_pages=0;
			}
			resultTableSet.setPage(String.valueOf(page));
			resultTableSet.setTotal(total_pages);
			resultTableSet.setRecords(String.valueOf(count));
		} catch (SQLException e) {
			if ( wid.isDebug ) {
				resultTableSet.setPage( wid.errProcess(e) );	
			}
			wid.kem(conn, ps, e, wid.toEType("SQLException")+errPars, wid.isPrint2Console );
		} catch (UnsupportedEncodingException e) {
			if ( wid.isDebug ) {
				resultTableSet.setPage( wid.errProcess(e) );	
			}
			wid.kem(conn, ps, e, wid.toEType("UnsupportedEncodingException")+errPars, wid.isPrint2Console );
		} catch (Exception e) {
			if ( wid.isDebug ) {
				resultTableSet.setPage( wid.errProcess(e) );	
			}
			wid.kem(conn, ps, e, wid.toEType("Exception")+errPars, wid.isPrint2Console );
		} finally {
			try {
				if (rs != null) {rs.close();}
				if (ps!= null) {ps.close();}
				if (conn!= null) {conn.close();}
			} catch (SQLException e) {
				System.out.println(wid.errProcess(e));
			}
		}
		
		if ("mappingSquadHost".equalsIgnoreCase(fromCall) ) {
			response.getWriter().write(new Gson().toJson(infoStrucs));
		} else {
			response.getWriter().write(new Gson().toJson(resultTableSet));	
		}
	}
}